package tom.client;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Label;

public class Clock extends Timer {
	private static final int SessionTimeout = 1500;   // 25 * 60seconds 
	private static final int msOfDay = 86400000;
	private static final int msOfHour = 3600000;
	private static final int msOfMinute = 60000;
	private static final int msOfSecond = 1000;
	private static final int[] dayOfMonths = { 31, 28, 31, 30, 31, 30, 31, 31,
			30, 31, 30, 31 };

	private int hour = 0;
	private int minute = 0;
	private int second = 0;
	private int day = 0;
	private int month = 0;
	private int year = 0;
	private long timeDiff = 0;
	private final Label labelTime;
	private final Label labelDate;
	private int count = 0;

	public void resetCount() {
		this.count = 0;
	}

	public Label getLabelDate() {
		return labelDate;
	}

	public Label getLabelTime() {
		return labelTime;
	}

	public Clock(long initTime) {
		labelTime = new Label();
		labelDate = new Label();
		timeDiff = initTime - System.currentTimeMillis();
		decodeDate(initTime);
		decodeTime();
		Clock.this.scheduleRepeating(1000);
	}

	private boolean isLeapYear(int year) {
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}

	private void decodeDate(long time) {
		int d = (int) (time / msOfDay) + 1;
		day = 1;
		month = 1;
		year = 1970;
		int y = 365;
		while (d > y) {
			year++;
			d -= y;
			if (isLeapYear(year))
				y = 366;
			else
				y = 365;
		}
		if (isLeapYear(year))
			dayOfMonths[1] = 29;
		else
			dayOfMonths[1] = 28;
		int i = 0;
		while (d > dayOfMonths[i]) {
			month++;
			d -= dayOfMonths[i];
			i++;
		}
		day = d;
		labelDate.setText(day + "/" + month + "/" + year);
	}

	private String s1;
	private String s2;
	
	public String getDT () {
		return "T" + month + day + hour + minute + second;
	}

	private void decodeTime() {
		long time = System.currentTimeMillis() + timeDiff;
		hour = (int) ((time % msOfDay / msOfHour) % 24);
		minute = (int) (time % msOfHour / msOfMinute);
		second = (int) (time % msOfMinute / msOfSecond);
		if (hour == 0 && minute == 0 && second == 0)
			decodeDate(time);

		if (minute < 10)
			s1 = ":0";
		else
			s1 = ":";
		if (second < 10)
			s2 = ":0";
		else
			s2 = ":";
		labelTime.setText(hour + s1 + minute + s2 + second);
		// labelTime
		// .setText(String.format("%02d:%02d:%02d", hour, minute, second));
	}

	@Override
	public void run() {
		decodeTime();
		if (count == SessionTimeout) {
			if (FormLogin.frmLogin.isConnected()) {
				IdlePopup.popup.showRelativeTo(FormLogin.frmLogin);
			}
			count = 0;
		}
		count++;
	}
}
